#!/usr/bin/env bash

# Test that env._.path configuration correctly orders paths, even when those
# paths already exist in the original PATH. This ensures user-configured paths
# take precedence over system defaults.
#
# Regression test for PATH ordering bug where env._.path entries were being
# filtered out if they already existed in __MISE_ORIG_PATH.
# Related to commit f4dca1b512321fce097125d06be6de8654361536

# Create a test directory structure to simulate custom and system bin dirs
mkdir -p "$HOME/custom/bin"
mkdir -p "$HOME/system/bin"

# Create dummy executables to test ordering
cat >"$HOME/custom/bin/test-tool" <<'EOF'
#!/usr/bin/env bash
echo "custom version"
EOF

cat >"$HOME/system/bin/test-tool" <<'EOF'
#!/usr/bin/env bash
echo "system version"
EOF

chmod +x "$HOME/custom/bin/test-tool"
chmod +x "$HOME/system/bin/test-tool"

# Add system/bin to PATH (simulating a system-provided tool that's already in PATH)
export PATH="$HOME/system/bin:$PATH"

# Verify system tool is found first before mise config
assert_contains "test-tool" "system version"

# Activate mise shell integration
eval "$(mise activate bash)"

# Create a mise config that explicitly prepends custom/bin via env._.path
# This should work even though system/bin is already in the original PATH
cat >mise.toml <<EOF
[env]
_.path = [
  "$HOME/custom/bin",
  "$HOME/system/bin",
]
EOF

# Apply the configuration via hook-env
eval "$(mise hook-env)"

echo "DEBUG: Final PATH=$PATH"
echo "DEBUG: __MISE_ORIG_PATH=${__MISE_ORIG_PATH:-not set}"

# Now the test-tool from custom/bin should be found first
assert_contains "test-tool" "custom version"

# Verify the PATH order by checking which comes first
WHICH_OUTPUT=$(which test-tool)
echo "DEBUG: which test-tool = $WHICH_OUTPUT"

# The path should be custom/bin (not system/bin)
if [[ $WHICH_OUTPUT == *"/custom/bin/test-tool" ]]; then
	echo "SUCCESS: custom/bin comes before system/bin in PATH"
else
	echo "FAIL: Expected custom/bin/test-tool but got $WHICH_OUTPUT"
	exit 1
fi
